import SwiftUI

struct AnimatedCounter: View {
    var value: Double
    @State private var displayedValue: Double = 0

    var body: some View {
        Text("$\(displayedValue, specifier: "%.2f")")
            .font(.system(size: 40, weight: .bold))
            .foregroundColor(.white)
            .onChange(of: value) { newValue in
                withAnimation(.easeOut(duration: 0.6)) {
                    displayedValue = newValue
                }
            }
            .onAppear {
                displayedValue = value
            }
    }
}

struct HomeView: View {
    @EnvironmentObject var expenseStore: ExpenseStore

    @State private var animateHeader = false
    @State private var animateList = false
    @State private var animateFloat = false

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack(alignment: .leading, spacing: 30) {

                    headerCard
                        .padding(.top, 10)
                        .opacity(animateHeader ? 1 : 0)
                        .offset(y: animateHeader ? 0 : 20)
                        .animation(.easeOut(duration: 0.6), value: animateHeader)
                        .offset(y: animateFloat ? 0 : -6)
                        .animation(.easeInOut(duration: 3).repeatForever(autoreverses: true), value: animateFloat)

                    HStack {
                        Text("Recent Transactions")
                            .font(.title2.bold())
                            .padding(.leading)
                            .opacity(animateHeader ? 1 : 0)
                            .offset(x: animateHeader ? 0 : -20)
                            .animation(.easeOut(duration: 0.6).delay(0.15), value: animateHeader)

                        Spacer()

                        NavigationLink {
                            AllTransactionsView()
                                .environmentObject(expenseStore)
                        } label: {
                            Text("View All")
                                .font(.subheadline)
                                .foregroundColor(.blue)
                        }
                        .padding(.trailing)
                        .opacity(animateHeader ? 1 : 0)
                        .offset(x: animateHeader ? 0 : 10)
                        .animation(.easeOut(duration: 0.6).delay(0.2), value: animateHeader)

                    }

                    if expenseStore.expenses.isEmpty {
                        emptyState
                    } else {
                        VStack(spacing: 16) {
                            ForEach(Array(expenseStore.expenses.sorted(by: { $0.amount > $1.amount }).enumerated()), id: \.element.id) { index, expense in
                                TransactionCard(expense: expense)
                                    .padding(.horizontal)
                                    .scaleEffect(animateList ? 1 : 0.96)
                                    .opacity(animateList ? 1 : 0)
                                    .offset(y: animateList ? 0 : 12)
                                    .animation(
                                        .spring(response: 0.45, dampingFraction: 0.8)
                                            .delay(0.06 * Double(index)),
                                        value: animateList
                                    )
                            }
                        }
                    }

                    Spacer(minLength: 80)
                }
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(.systemGray6),
                        Color(.systemGray5).opacity(0.5),
                        Color.white
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
            )
            .navigationTitle("MindFi")
            .onAppear {
                animateHeader = true
                animateList = true
                animateFloat = true
            }
        }
    }

    private var headerCard: some View {
        VStack(alignment: .leading, spacing: 14) {
            Text("This Month's Spending")
                .font(.headline)
                .foregroundColor(.white.opacity(0.85))

            AnimatedCounter(value: expenseStore.spentThisMonth)

            Text("\(expenseStore.expenses.count) transactions")
                .font(.subheadline)
                .foregroundColor(.white.opacity(0.75))

            ProgressView(value: min(expenseStore.spentThisMonth / 1000, 1.0))
                .tint(.white)
                .shadow(color: .white.opacity(0.6), radius: 6, y: 2)
                .animation(.easeOut(duration: 0.8), value: expenseStore.spentThisMonth)
        }
        .frame(maxWidth: .infinity)
        .padding(24)
        .background(
            LinearGradient(
                colors: [
                    Color.blue.opacity(0.85),
                    Color.purple.opacity(0.75)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
        .overlay(
            RoundedRectangle(cornerRadius: 26)
                .stroke(Color.white.opacity(0.18), lineWidth: 1.2)
        )
        .clipShape(RoundedRectangle(cornerRadius: 26, style: .continuous))
        .shadow(color: .purple.opacity(0.25), radius: 16, y: 8)
        .padding(.horizontal)
    }

    private var emptyState: some View {
        VStack(spacing: 12) {
            Image(systemName: "tray")
                .font(.system(size: 40))
                .foregroundColor(.secondary)
                .scaleEffect(animateList ? 1 : 0.6)
                .opacity(animateList ? 1 : 0)
                .animation(.spring(response: 0.5, dampingFraction: 0.75).delay(0.25), value: animateList)

            Text("No recent transactions")
                .font(.subheadline)
                .foregroundColor(.secondary)
                .opacity(animateList ? 1 : 0)
                .animation(.easeOut(duration: 0.4).delay(0.3), value: animateList)
        }
        .frame(maxWidth: .infinity)
        .padding(.top, 30)
    }
}
